# from icecream import ic
import json
import sys
import pandas as pd
import requests

from get_sql_res import gen_run_detail,gen_virtual_name
from get_response import gen_wafermap_config_mapping,gen_wafermap_config

def gen_info_dic(df_run_detail, sql_info):
    info_dic = {}
    # 基本信息
    info_dic['Lot ID'] = df_run_detail.iloc[0]['lot_id']
    # info_dic['Gross DIE'] = df_run_detail['input_cnt'].dropna().iloc[0]
    info_dic['device_id'] = df_run_detail.iloc[0]['device_id']
    info_dic['customer'] = df_run_detail.iloc[0]['customer']
    info_dic['factoryList'] = list(df_run_detail['factory'].drop_duplicates())
    info_dic['factorySiteList'] = list(
        df_run_detail['factory_site'].drop_duplicates())

    info_dic['test_area'] = df_run_detail.iloc[0]['test_area']
    info_dic['test_stage'] = df_run_detail.iloc[0]['test_stage']
    info_dic['real_test_stage'] = df_run_detail['real_test_stage'].dropna().iloc[0]
    df_lot_wafer = df_run_detail[['lot_id', 'wafer_id']
                            ].drop_duplicates(subset='wafer_id')
    info_dic['lot_wafer_id'] = df_lot_wafer.groupby(
        'lot_id')['wafer_id'].apply(list).to_dict()
    info_dic['rule_alias'] = list(df_run_detail['rule_alias'].drop_duplicates())

    # input&output dict
    dataset_lst = list(df_run_detail['updated_input_virtual_id'].drop_duplicates())
    dataset_dic_input={}
    dataset_dic_output={}
    for dataset_id in dataset_lst:
        input, output = gen_virtual_name(dataset_id, sql_info)
        dataset_dic_input[dataset_id]= input
        dataset_dic_output[dataset_id] = output
    info_dic['input_dict'] = dataset_dic_input
    info_dic['output_dict'] = dataset_dic_output

    # updated_input_virtual_id for mapping
    def gen_dataset_lst(df_run_detail):
        lst = []
        for i in list(df_run_detail['input_virtual_ids'].drop_duplicates()):
            if ',' in i:
                for j in i.split(','):
                    lst.append(int(j))
            else:
                lst.append(int(i))
        return lst
    dataset_dic_input_for_mapping={}
    dataset_dic_output_for_mapping={}
    for dataset_id in set(gen_dataset_lst(df_run_detail)+dataset_lst):
        input, output = gen_virtual_name(dataset_id, sql_info)
        dataset_dic_input_for_mapping[dataset_id]= input
        dataset_dic_output_for_mapping[dataset_id] = output
    info_dic['input_dict_for_mapping'] = dataset_dic_input_for_mapping
    info_dic['output_dict_for_mapping'] = dataset_dic_output_for_mapping

    # 所有的input_virtual_ids
    info_dic['input_virtual_ids']=list(df_run_detail['input_virtual_ids'].drop_duplicates())

    # rule_map
    df_rule_map = df_run_detail[['rule_alias', 'rule_key']].drop_duplicates(subset='rule_alias')
    info_dic['rule_map'] = dict(
        zip(df_rule_map['rule_alias'], df_rule_map['rule_key']))
    # dataSource
    info_dic['dataSourceList'] = list(
        df_run_detail['data_source'].drop_duplicates())
    # Gross DIE
    response = gen_wafermap_config(info_dic, sql_info)
    if len(response['data'])==0:
        info_dic['Gross DIE']='NA'
    else:
        info_dic['Gross DIE'] = response['data'][0]['grossDieCnt']
    # id对应rule
    info_dic['id_rule_map'] = {}
    for i in info_dic['input_virtual_ids']:
        if ',' in i:
            info_dic['id_rule_map'][i]=['Merge Bin']
        else:
            info_dic['id_rule_map'][i] = list(df_run_detail[df_run_detail['input_virtual_ids']==i]['rule_alias'].drop_duplicates())
    # df的行数和列数
    info_dic['df_info']={}

    return info_dic


if __name__ == '__main__':
    input_string = sys.argv[1]
    compressed_string = ''.join(input_string.split())
    python_dict = json.loads(compressed_string)

    # from icecream import ic
    # ic(python_dict)
    rule_run_record_id = python_dict['recordId']
    sql_info = {}
    sql_info['mysqlInfo'] = python_dict['mysqlInfo']
    sql_info['ckInfo'] = python_dict['ckInfo']
    sql_info['dasHost'] = python_dict['dasHost']
    re_file_path = python_dict['fileFullPath']

    df_run_detail = gen_run_detail(rule_run_record_id, sql_info)
    ##
    gen_info_dic(df_run_detail, sql_info)
